/*
 * @Author: szx
 * @Date: 2022-04-13 11:14:50
 * @LastEditTime: 2022-04-13 11:39:23
 * @Description:
 * @FilePath: \leetcode\剑指offerII\057\057.js
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @param {number} t
 * @return {boolean}
 */
var containsNearbyAlmostDuplicate = function (nums, k, t) {
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j <= i + k && j < nums.length; j++) {
            if (Math.abs(nums[j] - nums[i]) <= t) return true;
        }
    }
    return false;
};

var containsNearbyAlmostDuplicate = function (nums, k, t) {
    const n = nums.length;
    const map = new Map();
    const getID = (x, w = t + 1) => {
        return x < 0 ? Math.floor((x + 1) / w) - 1 : Math.floor(x / w);
    };
    for (let i = 0; i < n; ++i) {
        const x = nums[i];
        const id = getID(x);
        if (map.has(id)) return true;
        if (map.has(id - 1) && Math.abs(x - map.get(id - 1)) <= t) return true;
        if (map.has(id + 1) && Math.abs(x - map.get(id + 1)) <= t) return true;
        map.set(id, x);
        if (i >= k) map.delete(getID(nums[i - k]));
    }
    return false;
};
